﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace LRT.Nebula.Xml
{
    public static class XmlHelper
    {
        public static string Serialize<T>(T obj)
        {
            var serializer = new XmlSerializer(typeof(T));
            using(MemoryStream stream = new MemoryStream())
            {
                serializer.Serialize(stream, obj);
                return Encoding.UTF8.GetString(stream.ToArray());
            
            }
        }

        public static T Deserialize<T>(string s)
        {
            return Deserialize<T>(s, Encoding.UTF8);
        }

        public static T Deserialize<T>(string s, Encoding encoding)
        {


            var serializer = new XmlSerializer(typeof(T));
            

            using(MemoryStream stream = new MemoryStream(encoding.GetBytes(s)))
            {
                using (StreamReader reader = new StreamReader(stream, encoding))
                {
                    return (T)serializer.Deserialize(reader);  
                }
            }
        }
    }
}
